var envVersion = wx.getAccountInfoSync().miniProgram.envVersion

function __args() {
  var setting = {};
  if (arguments.length === 1 && typeof arguments[0] !== 'string') {
    setting = arguments[0];
  } else {
    setting.url = arguments[0];
    if (typeof arguments[1] === 'object') {
      setting.data = arguments[1];
      setting.callback = arguments[2];
    } else if (typeof arguments[1] === 'string') {//文件上传
      setting.filePath = arguments[1];
      setting.callback = arguments[2];
    } else {
      setting.callback = arguments[1];
    }
  }
  return setting;
}
function __loginjson(method, setting) {
  setting.method = method;
  setting.header = {
    'content-type': 'application/json',
    'sso': wx.getStorageSync('sso')
  };
  setting.complete = function (ret) { onComplete(ret, setting) };
  wx.request(setting);
}
function __json(method, setting) {
  // if (getApp().globalData && !(getApp().globalData.isNetConnected)) {
  //   wx.hideLoading()
  //   return
  // }
  setting.method = method;
  setting.header = {
    'content-type': 'application/json',
    'sso': wx.getStorageSync('sso'),
    'companyid': wx.getStorageSync(`${setting.url.includes('-book') ? 'book_company_id' : 'company_id'}`)
  };
  // setting.enableHttp2 = true
  // setting.enableCache = true
  setting.complete = function (ret) { onComplete(ret, setting) };
  wx.request(setting);
}

function __upload(setting) {
  setting.header = {
    "content-type": "multipart/form-data",
    'sso': wx.getStorageSync('sso')
  };
  setting.name = 'upload_image_file';
  setting.complete = function (ret) { onComplete(ret, setting) };
  setting.fail = function (ret) {
  }
  // wx.showToast({
  //   icon: "loading",
  //   title: "正在上传.."
  // });
  wx.uploadFile(setting);
}

function onComplete(ret, { callback, url, data }) {
  var errMsg = null;
  const common = require('common')
  // 排除接口报错上报，行为数据上报接口，招商支付接口
  const excludeUrl = url.indexOf('addlog/record') == -1 && url.indexOf('addlog/take') == -1 && url.indexOf('bank/pay') == -1
  if (ret.statusCode == 400 || ret.statusCode == 401 || ret.statusCode == 500) {
    errMsg = ret.data.message;
  } else {
    // if (ret.data && ret.data.errno && ret.data.errno == -1) {
    //   wx.hideLoading()
    //   if (getApp().globalData.isSystemUpdate) return
    //   getApp().globalData.isSystemUpdate = true
    //   wx.redirectTo({
    //     url: `/pages/common/announce?title=系统升级公告&content=${ret.data.errmsg}`,
    //   })
    //   return
    // }
    if (ret.errMsg.indexOf('request:fail') != -1 && ret.errMsg.indexOf('201') == -1 && excludeUrl) {
      // errMsg = ret.errMsg;
      // console.error(ret);
      // postJSON(common.storePath + 'addlog/record', {
      //   url, data,
      //   errlog: `errno:${ret.errno} ${ret.errMsg}`,
      //   sso: wx.getStorageSync('sso'),
      // }, res => { })
    } else if (ret.data && !ret.data.errno && excludeUrl) {
      postJSON(common.storePath + 'addlog/record', {
        url, data,
        errlog: ret.data,
        sso: wx.getStorageSync('sso'),
      })
    }
  }
  if (errMsg && excludeUrl && !(getApp().globalData.weakNet) && getApp().globalData.isNetConnected) {
    wx.showModal({
      title: '提示信息',
      content: errMsg,
      showCancel: false,
      success: res => {
        if (res.confirm) {
          wx.getNetworkType({
            success(resp) {
              console.log(resp)
            }
          })
        }
      }
    })
  }
  if (callback) {
    if (envVersion == 'release' && excludeUrl) {
      try {
        callback(ret)
      } catch (error) {
        // 线上环境js报错上报
        console.warn('======js报错======', error.toString());
        if (error.toString().includes('undefined is not an object')) {
          common.showToast('网络开小差啦，请稍候再试 [-3]');
          return
        }
        common.showToast("数据出错啦T_T，请稍候再试 [-3]");
        postJSON(common.storePath + 'feedback/record', {
          url, data,
          errlog_front: error.toString(),
          sso: wx.getStorageSync('sso'),
        }, res => { })
      }
    } else {
      callback(ret)
    }
  }
//   wx.$hideLoading()
}

function __uploadOSS(setting, callback) {
  wx.showToast({
    icon: "loading",
    title: "正在上传"
  });
  wx.uploadFile({
    url: setting.host,
    filePath: setting.filePath,
    name: 'file',
    formData: {
      'key': setting.key,
      'policy': setting.policy,
      'OSSAccessKeyId': setting.accessid,
      'success_action_status': '200', //让服务端返回200,不然，默认会返回204
      'signature': setting.signature,
    },
    success: function (res) {
      console.log(JSON.stringify(res))
      if (callback) {
        callback(res);
      }
    },
    fail: function (res) {
      console.log(JSON.stringify(res));
      require('common').showFail('上传失败');
    },
    complete: function (res) {
      wx.hideToast();
    }
  })
}

function postJSON() {
  __json('POST', __args.apply(this, arguments));
}

module.exports = {
  login: function () {
    __loginjson('POST', __args.apply(this, arguments));
  },
  getJSON: function () {
    __json('GET', __args.apply(this, arguments));
  },
  postJSON,
  del: function () {
    __json('DELETE', __args.apply(this, arguments));
  },
  put: function () {
    __json('PUT', __args.apply(this, arguments));
  },
  uploadFile: function () {
    __upload(__args.apply(this, arguments));
  },
  uploadOSS: function () {
    __uploadOSS(arguments[0], arguments[1]);
  }
}